<template>
  <div class="login-form">
    <div class="bg-elements">
      <div class="bg-element"></div>
      <div class="bg-element"></div>
      <div class="bg-element"></div>
    </div>
    <div class="login-box">

      <div class="login-input" v-if="thirdLogin.loginType === 'local'">
        <div class="system-title">
          <h1>公考同盟后台管理系统</h1>
          <p class="subtitle">Civil Service Exam Alliance Management System</p>
        </div>
        <el-form
          :model="dataForm"
          :rules="dataRule"
          label-position="top"
          ref="loginForm"
          @keyup.enter.stop="() => {}"
        >
          <el-col :span="24">
            <el-form-item prop="mobilePhone" label="" style="margin-top: 48px; margin-bottom: 25px">
              <el-input v-model="dataForm.mobilePhone" style="width: 100%" placeholder="请输入账号">
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="password" label="">
              <el-input
                v-model="dataForm.password"
                style="width: 100%"
                type="password"
                placeholder="请输入密码"
                show-password
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-button
            class="login-btn-submit"
            type="primary"
            size="large"
            @click="dataFormSubmit()"
            style="width: 100%; margin-top: 48px"
          >
            登录系统
          </el-button>
          <el-space
            direction="horizontal"
            style="justify-content: center; width: 100%; margin-top: 12px"
          >
            <!-- <el-text class="mx-1">还没有账号？</el-text>
            <el-link type="primary" style="font-size: 14px">立即注册</el-link> -->
          </el-space>
        </el-form>
        <!-- <div class="third-login">
          <div class="title">其他登录方式</div>
          <div class="login-icon-container">
            <div class="login-icon-item">
              <a
                style="font-size: 22px; color: #409EFF"
                title="微信"
                @click="onThirdLoginClick('wechat')"
              >
                <svg
                  focusable="false"
                  width="1em"
                  height="1em"
                  fill="currentColor"
                  aria-hidden="true"
                  viewBox="64 64 896 896"
                >
                  <path
                    d="M690.1 377.4c5.9 0 11.8.2 17.6.5-24.4-128.7-158.3-227.1-319.9-227.1C209 150.8 64 271.4 64 420.2c0 81.1 43.6 154.2 111.9 203.6a21.5 21.5 0 019.1 17.6c0 2.4-.5 4.6-1.1 6.9-5.5 20.3-14.2 52.8-14.6 54.3-.7 2.6-1.7 5.2-1.7 7.9 0 5.9 4.8 10.8 10.8 10.8 2.3 0 4.2-.9 6.2-2l70.9-40.9c5.3-3.1 11-5 17.2-5 3.2 0 6.4.5 9.5 1.4 33.1 9.5 68.8 14.8 105.7 14.8 6 0 11.9-.1 17.8-.4-7.1-21-10.9-43.1-10.9-66 0-135.8 132.2-245.8 295.3-245.8zm-194.3-86.5c23.8 0 43.2 19.3 43.2 43.1s-19.3 43.1-43.2 43.1c-23.8 0-43.2-19.3-43.2-43.1s19.4-43.1 43.2-43.1zm-215.9 86.2c-23.8 0-43.2-19.3-43.2-43.1s19.3-43.1 43.2-43.1 43.2 19.3 43.2 43.1-19.4 43.1-43.2 43.1zm586.8 415.6c56.9-41.2 93.2-102 93.2-169.7 0-124-120.8-224.5-269.9-224.5-149 0-269.9 100.5-269.9 224.5S540.9 847.5 690 847.5c30.8 0 60.6-4.4 88.1-12.3 2.6-.8 5.2-1.2 7.9-1.2 5.2 0 9.9 1.6 14.3 4.1l59.1 34c1.7 1 3.3 1.7 5.2 1.7a9 9 0 006.4-2.6 9 9 0 002.6-6.4c0-2.2-.9-4.4-1.4-6.6-.3-1.2-7.6-28.3-12.2-45.3-.5-1.9-.9-3.8-.9-5.7.1-5.9 3.1-11.2 7.6-14.5zM600.2 587.2c-19.9 0-36-16.1-36-35.9 0-19.8 16.1-35.9 36-35.9s36 16.1 36 35.9c0 19.8-16.2 35.9-36 35.9zm179.9 0c-19.9 0-36-16.1-36-35.9 0-19.8 16.1-35.9 36-35.9s36 16.1 36 35.9a36.08 36.08 0 01-36 35.9z"
                  ></path>
                </svg>
              </a>
            </div>
          </div>
        </div> -->
      </div>
      <div class="login-input" v-else>
        <div class="login-back-local">
          <el-icon
            title="返回账号密码登录"
            style="font-size: 18px"
            @click="onThirdLoginClick('local')"
          >
            <Back />
          </el-icon>
          <span class="title">{{ thirdLoginTitle }}登录</span>
          <component
            :is="thirdLoginComponent"
            @success="handleOAuthSuccess"
            @error="handleOAuthError"
          ></component>
        </div>
      </div>
    </div>
    <div class="footer">
      <p>Copyright © 2024 公考同盟后台管理系统 All Rights Reserved</p>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'Login',
};
</script>

<script setup lang="ts">
import type { FormInstance } from 'element-plus';
import { Router, useRouter } from 'vue-router';
import bkImg from '@/assets/img/login_icon2.png';
import { encrypt, setToken, treeDataTranslate } from '@/common/utils/index';
import { loginParam } from '@/types/upms/login';
import { useLoginStore, useLayoutStore } from '@/store';
import LoginController from '@/api/system/LoginController';
import OAuthController from '@/api/system/OAuthController';
import FormulaEditor from '@/components/FormulaEditor/index.vue';
import DinkTalkLogin from '@/components/DingTalk/login.vue';
import FeishuLogin from '@/components/Feishu/login.vue';
import WeWorkLogin from '@/components/WeWork/login.vue';
import WeChatLogin from '@/components/WeChat/login.vue';

const loginForm = ref<FormInstance>();

const loginStore = useLoginStore();
const layoutStore = useLayoutStore();
const router: Router = useRouter();

const dataForm = reactive({
  mobilePhone: '',
  password: '',
});

const dataRule = {
  mobilePhone: [{ required: true, message: '帐号不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
};

const thirdLogin = ref({
  // 第三方登录类型, local-本地，dingtalk-钉钉 feishu-飞书 wework-企业微信 wechat-微信（关注公众号）
  loginType: 'local',
  // oauth授权成功，但是未找到绑定的账号时，生成该token
  thirdLoginToken: null,
});

const thirdLoginComponent = computed(() => {
  switch (thirdLogin.value.loginType) {
    case 'dingtalk':
      return DinkTalkLogin;
    case 'feishu':
      return FeishuLogin;
    case 'wework':
      return WeWorkLogin;
    case 'wechat':
      return WeChatLogin;
    default:
      return 'div';
  }
});

const thirdLoginTitle = computed(() => {
  switch (thirdLogin.value.loginType) {
    case 'dingtalk':
      return '钉钉';
    case 'feishu':
      return '飞书';
    case 'wework':
      return '企业微信';
    case 'wechat':
      return '微信';
    default:
      return '';
  }
});

const onThirdLoginClick = (type: string) => {
  thirdLogin.value.loginType = type;
};

const handleOAuthSuccess = data => {
  console.log('第三方登录成功', data);
  layoutStore.setMenuList(treeDataTranslate(data.data.menuList, 'menuId', 'parentId'));
  delete data.data.menuList;

  loginStore.setUserInfo(data.data);
  setToken(data.data.tokenData);
  layoutStore.setCurrentMenu(null);
  router.replace({ name: 'main' });
};

const handleOAuthError = err => {
  console.error('第三方登录失败', err);
  if (err && err.errorCode === 'DATA_NOT_EXIST') {
    thirdLogin.value.thirdLoginToken = err.data.token;
    onThirdLoginClick('local');
  }
};

const loginAndBind = params => {
  params.token = thirdLogin.value.thirdLoginToken;
  thirdLogin.value.thirdLoginToken = null;
  OAuthController.doLoginAndBind(params, { showMask: false })
    .then(data => {
      layoutStore.setMenuList(treeDataTranslate(data.data.menuList, 'menuId', 'parentId'));
      delete data.data.menuList;

      loginStore.setUserInfo(data.data);
      setToken(data.data.tokenData);
      layoutStore.setCurrentMenu(null);
      router.replace({ name: 'main' });
    })
    .catch(e => {
      console.error(e);
    });
};

const dataFormSubmit = () => {
  loginForm.value?.validate((valid: boolean) => {
    if (valid) {
      login();
    }
  });
};

const login = function (verifyParams: { captchaVerification: string } | null = null) {
  let params: loginParam = {
    loginName: dataForm.mobilePhone,
    password: encrypt(dataForm.password),
    captchaVerification: verifyParams?.captchaVerification,
  };
  setToken(null);
  LoginController.login(params)
    .then(data => {
      //console.log('login >>>', data);
      if (data.data.menuList) {
        layoutStore.setMenuList(treeDataTranslate(data.data.menuList, 'menuId', 'parentId'));
        delete data.data.menuList;
      }
      setToken(data.data.tokenData);
      layoutStore.setCurrentMenu(null);
      layoutStore.clearAllTags();
      if (data.data.tokenData) {
        delete data.data.tokenData;
      }
      loginStore.setUserInfo(data.data);
      // 登录成功跳转页面
      router.replace({ name: 'main' });
    })
    .catch(e => {
      console.error(e);
    });
};
</script>

<style lang="scss">
.login-form {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);

  &::before,
  &::after {
    content: '';
    position: absolute;
    width: 300px;
    height: 300px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    z-index: 1;
  }

  &::before {
    top: -100px;
    right: -100px;
    animation: float 8s ease-in-out infinite;
  }

  &::after {
    bottom: -100px;
    left: -100px;
    animation: float 8s ease-in-out infinite reverse;
  }

  .bg-elements {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 1;

    .bg-element {
      position: absolute;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 50%;

      &:nth-child(1) {
        width: 100px;
        height: 100px;
        top: 20%;
        left: 10%;
        animation: float 6s ease-in-out infinite;
      }

      &:nth-child(2) {
        width: 150px;
        height: 150px;
        top: 60%;
        right: 15%;
        animation: float 7s ease-in-out infinite reverse;
      }

      &:nth-child(3) {
        width: 80px;
        height: 80px;
        bottom: 20%;
        left: 20%;
        animation: float 5s ease-in-out infinite;
      }
    }
  }

  @keyframes float {
    0%, 100% {
      transform: translateY(0) rotate(0deg);
    }
    50% {
      transform: translateY(-20px) rotate(5deg);
    }
  }

  .system-title {
    text-align: center;
    margin-bottom: 40px;
    position: relative;
    z-index: 2;
    h1 {
      font-size: 28px;
      color: #67c23a;
      margin-bottom: 8px;
      font-weight: 600;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    .subtitle {
      font-size: 14px;
      color: #666;
    }
  }
  .login-box {
    display: flex;
    align-items: center;
    height: 499px;
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.95);
    box-shadow: 0 8px 32px rgba(103, 194, 58, 0.15);
    position: relative;
    z-index: 2;
    backdrop-filter: blur(10px);
    .login-input {
      display: flex;
      width: 448px;
      padding: 46px 40px;
      background-color: #fff;
      border-radius: 16px;
      flex-direction: column;
      .title {
        margin-bottom: 5px;
        font-size: 32px;
        color: #67c23a;
        font-weight: bold;
      }
      .desc {
        margin-bottom: 24px;
        font-size: 18px;
        color: #666;
      }
      .third-login {
        text-align: center;
        .title {
          color: #999;
          font-size: 14px;
          font-weight: normal;
          margin-top: 25px;
          margin-bottom: 25px;
          position: relative;
          &::before,
          &::after {
            content: '';
            position: absolute;
            top: 50%;
            width: 60px;
            height: 1px;
            background: #eee;
          }
          &::before {
            left: 50px;
          }
          &::after {
            right: 50px;
          }
        }
        .login-icon-container {
          display: flex;
          align-items: center;
          justify-content: center;
          .login-icon-item {
            a {
              cursor: pointer;
              transition: all 0.3s;
              &:hover {
                transform: scale(1.1);
              }
            }
          }
        }
      }
      .login-back-local {
        i {
          cursor: pointer;
        }
        .title {
          margin-left: 10px;
        }
      }
    }
    .img-box {
      position: relative;
      height: 100%;
      margin-right: 109px;
      .img-title {
        position: absolute;
        top: -80px;
        right: 0;
        left: 0;
        display: none;
        width: 375px;
        margin: 0 auto;
      }
    }
  }
  .footer {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    height: 44px;
    font-size: 14px;
    color: rgba(255, 255, 255, 0.8);
    background-color: rgba(0, 0, 0, 0.1);
    p {
      text-align: center;
      line-height: 44px;
      margin: 0;
    }
  }
  .el-form-item__label {
    color: #333;
  }
  .el-input__inner {
    height: 44px !important;
    border-radius: 4px;
    &:focus {
      border-color: #67c23a;
      box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.1);
    }
  }
  .login-btn-submit {
    height: 44px;
    font-size: 16px;
    background: #67c23a;
    border-color: #67c23a;
    &:hover {
      background: #85ce61;
      border-color: #85ce61;
    }
  }
}

.logo-right {
  a,
  span {
    font-size: 16px;
    font-weight: normal;
    color: #666;
  }
}
</style>
